package com.silky.common.utils;


import com.silky.common.bean.JdbcConfig;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * jdbc 数据库连接工具类
 */
@Slf4j
public class JdbcUtil {
    /**
     * 获取数据库连接
     * @param jdbcConfig
     * @return
     * @throws Exception
     */
    public static Connection getConnection(JdbcConfig jdbcConfig) throws Exception {
            // 加载JDBC驱动
            Class.forName(jdbcConfig.getDriverClassName());

            // 创建数据库连接
            String url = jdbcConfig.getUrl();
            String user = jdbcConfig.getUsername();
            String password = jdbcConfig.getPassword();
            Connection conn = DriverManager.getConnection(url, user, password);

            return conn;

    }

    /**
     * 关闭连接
     * @param conn
     * @throws SQLException
     */
    public static void closeConnection(Connection conn) throws SQLException {
        if(conn!=null){
            conn.close();
        }
    }
}
